package com.hxzy.springbootrocketproducer.service;

import com.alibaba.fastjson.JSONObject;
import com.hxzy.springbootrocketproducer.dto.User;
import lombok.extern.log4j.Log4j2;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

/**
 * 消息生产者
 * @author Fan
 */
@Log4j2
@Component
@SuppressWarnings("all")
public class ProducerService {

    /**
     * rocketmq.spring.core 的对象rocketMQTemplate
     */
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    // 建议正常规模项目统一用一个TOPIC
    private static final String topic = "RLT_DEMO_TOPIC";


    /**
     * 使用模板类发送消息
     * destination 目的地
     * @param user
     */
    public void sendMessage(User  user){
        //message(topic,tag,内容)  框架   topic:tag
       this.rocketMQTemplate.convertAndSend(topic+":user01", user);
    }


    /**
     * 发送同步消息（sendResult为返回的发送结果）
     * rocketmq中的类SendResult 传入String-->message
     */
    public SendResult sendMsg(String msgBody) {
        SendResult sendResult = rocketMQTemplate.syncSend(topic+":tag01", MessageBuilder.withPayload(msgBody).build());
        log.info("【sendMsg】sendResult={}", JSONObject.toJSONString(sendResult));
        return sendResult;
    }

    /**
     * 发送异步消息（适合对响应时间敏感的业务场景）
     */
    public void sendAsyncMsg(String msgBody) {
        rocketMQTemplate.asyncSend(topic+":tag02", MessageBuilder.withPayload(msgBody).build(), new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                // 处理消息发送成功逻辑
                //转换成fastjson对象
                log.info("异步消息=\n {}", JSONObject.toJSONString(sendResult));
            }

            @Override
            public void onException(Throwable throwable) {
                // 处理消息发送异常逻辑
                log.info("异步消息=\n {}", throwable.getMessage());
            }
        });
    }

    /**
     * 发送延时消息<br/>
     * 在start版本中 延时消息一共分为18个等级分别为：1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h
     * 同步发送消息
     */
    public void sendDelayMsg(String msgBody, int delayLevel) {
        rocketMQTemplate.syncSend(topic+":tag03", MessageBuilder.withPayload(msgBody).build(), 2000L, delayLevel);
    }

    /**
     * 发送单向消息（不关心发送结果，如日志）
     */
    public void sendOneWayMsg(String msgBody) {
        rocketMQTemplate.sendOneWay(topic+":tag04", MessageBuilder.withPayload(msgBody).build());
    }



}
